package com.lsht.system.service.impl.siwei;

import com.lsht.common.config.LshtConfig;
import com.lsht.common.exception.ServiceException;
import com.lsht.common.utils.FileUploadTool;
import com.lsht.common.utils.StringUtils;
import com.lsht.common.utils.uuid.IdUtils;
import com.lsht.system.domain.siwei.SiweiPoint;
import com.lsht.system.domain.siwei.business.SiweiPointBus;
import com.lsht.system.mapper.SysDeptMapper;
import com.lsht.system.mapper.siwei.SiweiDeviceMapper;
import com.lsht.system.mapper.siwei.SiweiPointMapper;
import com.lsht.system.service.siwei.SiweiPointService;
import com.lsht.system.util.NullUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 点位管理Service业务层处理
 *
 * @author zyc
 * @date 2024-08-14
 */
@Service
public class SiweiPointServiceImpl implements SiweiPointService {
    @Autowired
    private SiweiPointMapper siweiPointMapper;


    @Autowired
    private SiweiDeviceMapper siweiDeviceMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;


    /**
     * 新增点位管理
     *
     * @param siweiPoint 点位管理
     * @return 结果
     */
    @Override
    public int genAdd(SiweiPoint siweiPoint, MultipartFile file) {
        String deviceId = siweiPoint.getDeviceId();

//        siweiPoint.setCreateTime(new Date());
//        siweiPoint.setCreateTime(new Date());
        final String logoUrl = LshtConfig.getProfile() + File.separator + "siweiPoint" + File.separator;
        if (NullUtil.isNotEmpty(file)) {
            //设置文件路径
            String originalFilename = file.getOriginalFilename();
            // 上传并返回新文件名称
            try {
                String fileName = FileUploadTool.upload(logoUrl, file, originalFilename);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String replace = logoUrl.replace(LshtConfig.getProfile(), "/profile") + originalFilename;
            siweiPoint.setPointImgUrl(replace.replaceAll("\\\\", "/"));
        }
        //id 不为空走修改
        if (NullUtil.isNotEmpty(siweiPoint.getId())) {
            siweiPoint.setUpdateTime(new Date());
            //根据点位绑定的设备id 查看是否修改绑定的设备，若变了，去修改原设备状态为未使用
            String originalDeviceId = siweiPointMapper.getOriginalDeviceId(siweiPoint.getId());
            String newDeviceId = siweiPoint.getDeviceId();
            if (StringUtils.isNotEmpty(originalDeviceId)) {
                //对比新旧是否一致，不一致修改旧的状态为未使用
                if (!originalDeviceId.equals(newDeviceId)) {
                    //修改旧设备状态为未使用
                    siweiPointMapper.updateDeviceStatus(originalDeviceId, 0);
                    //修改绑定的点位为空
                    siweiDeviceMapper.updatePointIdById(originalDeviceId, null);
                    //修改新设备状态为已使用
                    siweiPointMapper.updateDeviceStatus(newDeviceId, 1);
                    siweiDeviceMapper.updatePointIdById(newDeviceId, siweiPoint.getId());
                }

            } else {
                //修改新设备状态为已使用
                siweiPointMapper.updateDeviceStatus(newDeviceId, 1);
                siweiDeviceMapper.updatePointIdById(deviceId, siweiPoint.getId());
            }
            //若用户是admin 则设置userId为null(因为用户id也跟着修改了,变成1的话  用户就无法与地图匹配了)
            return siweiPointMapper.genUpdateById(siweiPoint);
        }
        if (StringUtils.isNotEmpty(deviceId)) {
            //设备id不为空 修改设备使用状态为使用
            siweiPointMapper.updateDeviceStatus(deviceId, 1);
            //修改设备
            siweiDeviceMapper.updatePointIdById(deviceId, siweiPoint.getId());
        }
        siweiPoint.setId(IdUtils.simpleUUID());
        siweiPoint.setShowHidden(0);
        return siweiPointMapper.genAdd(siweiPoint);
    }

    @Override
    public int addPointByApp(SiweiPoint siweiPoint) {
        siweiPoint.setShowHidden(0);
//        siweiPoint.setCreateTime(new Date());
        String deviceId = siweiPoint.getDeviceId();
        try {
            String base64Image = siweiPoint.getImage();
            if (StringUtils.isNotEmpty(base64Image)) {
                String imageData = base64Image.split(",")[1]; // Remove data URL prefix
                byte[] decodedBytes = Base64.getDecoder().decode(imageData);
                String fileName = LshtConfig.getProfile() + File.separator + "siweiPoint" + File.separator + System.currentTimeMillis() + ".png";
                String directoryPath = LshtConfig.getProfile() + File.separator + "siweiPoint";
                File directory = new File(directoryPath);
                if (!directory.exists()) {
                    directory.mkdirs(); // 创建目录
                }
                File file = new File(fileName);
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    fos.write(decodedBytes);
                }
                String replace = fileName.replace(LshtConfig.getProfile(), "/profile");
                siweiPoint.setPointImgUrl(replace.replaceAll("\\\\", "/"));
                //id 不为空走修改
                if (NullUtil.isNotEmpty(siweiPoint.getId())) {
                    siweiPoint.setUpdateTime(new Date());
                    String originalDeviceId = siweiPointMapper.getOriginalDeviceId(siweiPoint.getId());
                    String newDeviceId = siweiPoint.getDeviceId();
                    if (StringUtils.isNotEmpty(originalDeviceId)) {
                        //对比新旧是否一致，不一致修改旧的状态为未使用
                        if (!originalDeviceId.equals(newDeviceId)) {
                            //修改旧设备状态为未使用
                            siweiPointMapper.updateDeviceStatus(originalDeviceId, 0);
                            //修改绑定的点位为空
                            siweiDeviceMapper.updatePointIdById(originalDeviceId, null);
                            //修改新设备状态为已使用
                            siweiPointMapper.updateDeviceStatus(newDeviceId, 1);
                            siweiDeviceMapper.updatePointIdById(newDeviceId, siweiPoint.getId());
                        }

                    } else {
                        //修改新设备状态为已使用
                        siweiPointMapper.updateDeviceStatus(newDeviceId, 1);
                        siweiDeviceMapper.updatePointIdById(deviceId, siweiPoint.getId());
                    }
                    return siweiPointMapper.genUpdateById(siweiPoint);
                }
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
//            return ResponseEntity.status(500).body("Error saving image");
        }
        if (StringUtils.isNotEmpty(deviceId)) {
            //设备id不为空 修改设备使用状态为使用
            siweiPointMapper.updateDeviceStatus(deviceId, 1);
            //修改设备
            siweiDeviceMapper.updatePointIdById(deviceId, siweiPoint.getId());
        }
        siweiPoint.setId(IdUtils.simpleUUID());
        return siweiPointMapper.genAdd(siweiPoint);
    }

    /**
     * 删除点位管理信息
     *
     * @param
     * @return 结果
     */
    @Override
    public int genDeleteById(List<String> idList) {
        //根据id查询设备ID 将设备状态改为未使用
        List<String> deviceList = siweiPointMapper.getPointDeviceList(idList);
        if (NullUtil.isNotNull(deviceList)) {
            for (String s : deviceList) {
                siweiPointMapper.updateDeviceStatus(s, 0);
            }
        }
        return siweiPointMapper.genDeleteById(idList);
    }

    /**
     * 修改点位管理
     *
     * @param siweiPoint 点位管理
     * @return 结果
     */
    @Override
    public int genUpdateById(SiweiPoint siweiPoint) {
        siweiPoint.setUpdateTime(new Date());
        return siweiPointMapper.genUpdateById(siweiPoint);
    }

    /**
     * 查询点位管理列表
     *
     * @param siweiPoint 点位管理
     * @param deptId
     * @return 点位管理
     */
    @Override
    public List<SiweiPoint> genQueryList(SiweiPoint siweiPoint, Long deptId) {
        //根据部门ID  判断
        //拿原先的id去和新传的对比，
        List<Long> objects = new ArrayList<>();
        objects.add(deptId);
        if (NullUtil.isNull(deptId)) {
            siweiPoint.setDeptIdList(null);
        } else {
            siweiPoint.setDeptIdList(objects);
        }
        List<String> date = siweiPoint.getDate();
//        if (NullUtil.isNotNull(deptId)) {
//            Long parentDeptId = getParentDeptId(deptId);
//            objects.add(parentDeptId);
//
//        }

        if (NullUtil.isNotNull(date) && date.size() > 0) {
            siweiPoint.setBeginTime(date.get(0));
            siweiPoint.setEndTime(date.get(1));
        }
        return siweiPointMapper.genQueryList(siweiPoint);
    }

    /**
     * 封装查询上级部门Id方法
     */
    private Long getParentDeptId(Long deptId) {
        return sysDeptMapper.getParentDeptId(deptId);
    }

    /**
     * 根据id查询点位详情信息
     *
     * @param siweiPoint
     * @return
     */
    @Override
    public SiweiPoint genQueryById(SiweiPoint siweiPoint) {
        return siweiPointMapper.genQueryById(siweiPoint);
    }

    /**
     * 大屏查询点位数量及较昨日新增数
     *
     * @param siweiPoint
     * @return
     */
    @Override
    public HashMap pointStatistics(SiweiPoint siweiPoint) {
        HashMap<Object, Object> map = new HashMap<>();
        //查询点位数量
        Integer pointNum = siweiPointMapper.getCountPointNum(siweiPoint);
        map.put("pointNum", pointNum);
        //获取昨日开始和结束时间
        String[] yesterdayStartAndEndTime = SiweiDateUtils.getYesterdayStartAndEndTime();
        //查询点位数量昨日日新增数
        Integer pointAddNum = siweiPointMapper.getNumByYesterday(yesterdayStartAndEndTime[0], yesterdayStartAndEndTime[1],siweiPoint.getDeptId());
        map.put("pointAddNum", pointAddNum);
        return map;
    }

    /**
     * 大屏按照年份进行点位状态为异常的个数，并返回同比去年
     *
     * @param siweiPoint
     * @return
     */
    @Override
    public HashMap abnormalPointDetails(SiweiPoint siweiPoint) {
        Integer parameterType = siweiPoint.getParameterType();
        // 创建一个新的 HashMap 来存放最终结构数据
        HashMap<String, Object> resultMap = new HashMap<>();
        Integer detailsType = siweiPoint.getDetailsType();
        //根据部门id  查询点位 获取点位id
        if (NullUtil.isNotNull(parameterType)) {
            switch (parameterType) {
                //按年查询
                case 0:
                    List<HashMap> yearList = siweiPointMapper.abnormalPointByYear(detailsType,siweiPoint.getDeptId());
                    resultMap.put("type", "year");
                    resultMap.put("values", yearList);
                    return resultMap;
                //按季查询
                case 1:
                    List<HashMap> quarterlList = siweiPointMapper.abnormalPointByQuarter(detailsType,siweiPoint.getDeptId());
                    resultMap.put("type", "quarter");
                    resultMap.put("values", quarterlList);
                    return resultMap;
                //按月查询
                case 2:
                    List<HashMap> monthList = siweiPointMapper.abnormalPointByMonth(detailsType,siweiPoint.getDeptId());
                    resultMap.put("type", "month");
                    resultMap.put("values", monthList);
                    return resultMap;
                default:
                    System.out.println("Unknown value");
                    break;
            }
        }
        return null;
//        //开始判断根据什么查 年度  季度 月份
//        Integer year = siweiPoint.getYear();
//        //季度
//        Integer quarter = siweiPoint.getQuarter();
//        //月份
//        Integer month = siweiPoint.getMonth();
//        //年度不为空 根据年份查询
//        if (NullUtil.isNotEmpty(year)) {
//            return siweiPointMapper.abnormalPointDetails(siweiPoint);
//            //季度不为空 根据季度查询
//        } else if (NullUtil.isNotEmpty(quarter)) {
//            //开始判断季度  获取其月份
//            return siweiPointMapper.abnormalPointDetailsByQuarter(siweiPoint);
//        } else {
//            //根据月份查询
//            return siweiPointMapper.abnormalPointDetailsByMonth(siweiPoint);
//        }
    }

    /**
     * 大屏按照所属区域分组展示异常点位的个数
     *
     * @param siweiPoint
     * @return
     */
    @Override
    public List<HashMap> abnormalPointByRegion(SiweiPoint siweiPoint) {
        return siweiPointMapper.abnormalPointByRegion(siweiPoint);
    }


    @Override
    public String importPoint(List<SiweiPointBus> pointList, String operName) {
        if (StringUtils.isNull(pointList) || pointList.size() == 0) {
            throw new ServiceException("导入点位数据不能为空！");
        }
        StringBuilder successMsg = new StringBuilder();
        int successNum = 0;
        for (SiweiPointBus siweiPointBus : pointList) {
            SiweiPoint siweiPoint = new SiweiPoint();
            siweiPoint.setId(IdUtils.simpleUUID());
            siweiPoint.setCreateUser(operName);
//            siweiPoint.setCreateTime(new Date());
            siweiPoint.setPointName(siweiPointBus.getPointName());
            siweiPoint.setPointAddress(siweiPointBus.getPointAddress());
            siweiPoint.setRegion(siweiPointBus.getRegion());
            siweiPoint.setLat(siweiPointBus.getLat());
            siweiPoint.setLng(siweiPointBus.getLng());
            siweiPointMapper.genAdd(siweiPoint);
            successNum++;
            successMsg.append("<br/>" + successNum + "、点位 " + siweiPoint.getPointName() + " 导入成功");
        }
        return successMsg.toString();
    }
}
